/*
 * @Descripttion: 
 * @Author: junhuafly
 * @Date: 2020-03-04 16:53:02
 * @LastEditors: junhuafly
 * @Email: junhuafly@163.com
 * @LastEditTime: 2020-04-10 17:00:50
 */
// pages/address/edit/index.js
import area from '../../../plus/area.js'
import {
  userAPI
} from './../../../api/user'
import {
  returnStatus,
} from './../../../utils/index'
var appInst = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    showAddress: false,
    areas: area,
    form: {},
    area: '',
    errorPhone: ''
  },
  cancelChoose() {
    this.setData({
      showAddress: false
    })
  },
  // 操作地址
  saveAddress() {
    if (this.data.errorPhone) return
    this.data.form.isDefault = this.data.form.isDefault ? 1 : 0
    userAPI.handleCustomerAddress({
      method: this.data.form.addressId ? 'put' : 'post',
      ...this.data.form
    }).then(async _ => {
      const res = returnStatus(_)
      if (res) {
        this.eventChannel.emit('refreshAddress', {
          data: 'success'
        });
        wx.navigateBack();
      }
    })
  },
  showAddressPopup() {
    this.setData({
      showAddress: true
    })
  },
  hideAddressPopup() {
    this.setData({
      showAddress: false
    })
  },
  changeArea({
    detail
  }) {
    const v = detail.values
    this.setData({
      area: `${v[0].name} ${v[1]?v[1].name:''} ${v[2]?v[2].name:''}`
    })
  },
  onChange({
    detail,
    currentTarget
  }) {
    const target = `form.${currentTarget.dataset.target}`
    if (currentTarget.dataset.target === 'phone') {
      this.setData({
        errorPhone: !(/^1[3456789]\d{9}$/.test(detail)) ? '手机号输入不正确' : ''
      })
    }
    this.setData({
      [target]: detail
    })
  },
  confirmArea({
    detail
  }) {
    const v = detail.values
    this.setData({
      'form.province': v[0].name,
      'form.city': v[1].name,
      'form.district': v[2].name,
      showAddress: false
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    appInst.setTitle('地址编辑')
    this.eventChannel = this.getOpenerEventChannel()
    this.eventChannel.on('addressInfo', ({
      data
    }) => {
      this.setData({
        form: data,
        area: data.province + ' ' + data.city + ' ' + data.district
      })
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})